const Editate = (function () {

    let Editate = function () {};
    let _this = Editate.prototype;

    let _editate_DOM = {};
    let _editate_data = {};

    /**
     * 创建上传，成功后执行回调 callback(src)
     */
    _this.uploader = function (data, callback) {
        switch (data.__pictureSelectMode) {
            case "localxcut":
                _this.uploaderOnLocalxCut(data, callback);
                break;
            case "wechat":
                _this.uploaderOnWechat(data, callback);
        }
    };
    
    /** 
     * 通过本地图片控件上传图片并支持裁剪
     */
    _this.uploaderOnLocalxCut = function (data, callback) {
        let value = _editate_DOM["7"].__data.value;
        let choosed_length = 0;
        if (value != "") {
            choosed_length = Util.type(value) == "string" ? value.split(",").length : value.length;
        }
        let imgsArr = [];

        // 如果达到上限，不再打开上传
        if (data.max_image_length - choosed_length <= 0) {
            return;
        }

        // 尺寸方式
        let size = data.original.uploadImgSize;

        // size = 1时使用微信上传方式
        if (size == 1) {
            _this.uploaderOnWechat(data, callback);
            return;
        }

        let InputFile = Render.create(`<input type="file" accept="image/*" style="display:none"/>`);
        let OperaDom  = Render.create(`<div></div>`);
            OperaDom.style.cssText = "position:absolute;z-index:2001;bottom:1rem;display:flex;width:100%;";
        let OkButton  = Render.create(`<button class="btn btn-primary" style="margin:1rem">截取</button>`);
        let CancelButton  = Render.create(`<button class="btn btn-light" style="margin:1rem">取消</button>`);

        CancelButton.addEventListener("click", function () {
            ClipContainer.style.visibility = "hidden";
        });
        OkButton.addEventListener("click", function () {
            ClipContainer.style.visibility = "hidden";
        });

        OperaDom.appendChild(OkButton);
        OperaDom.appendChild(CancelButton);

        let ClipView  = Render.create(`<div></div>`);
        ClipView.style.cssText = "height:86%;";

        let ClipContainer = Render.create(`<div></div>`);
        ClipContainer.style.cssText = "visibility:hidden;position:fixed;z-index:20;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,.4);";
        ClipContainer.appendChild(ClipView);
        ClipContainer.appendChild(OperaDom);

        document.body.appendChild(ClipContainer);

        var sizeBox = {
                "2": [295, 413],
                "3": [413, 626],
                "4": [358, 441]
            },
            adaptive = {
                "2": ["90%"],
                "3": ["90%"],
                "4": ["90%"]
            };
        
        let pc = new PhotoClip(ClipView, {
            width: sizeBox[size][0],
            height: sizeBox[size][1],
            size: sizeBox[size],
            adaptive: adaptive[size],
            outputSize: sizeBox[size],
            file: InputFile,
            // file: "#tempClipValue",
            view: ClipView,
            ok: OkButton,
            loadStart: function(file) {},
            loadComplete: function(file) {
                ClipContainer.style.visibility = "visible";
            },
            done: function(base64) {
                pc.clear();

                let loading = Component.loading("图片裁剪中").render();
                Api.uploadStudImage({
                    base64: base64,
                    width: sizeBox[size][0],
                    height: sizeBox[size][1],
                }, function (data) {
                    let name = data.data;
                    let changeImgUrl = function (url) {
                        var imgName = url.split(".")[0];
                        imgName = "/esb/res/pic/" + Math.floor(+imgName / 10000) + "/" + Math.floor(+imgName / 100) + "/" + url;
                        return imgName;
                    }
                    loading.hide();
                    callback && callback([changeImgUrl(name)]);
                });
            },
            fail: function(msg) {
                Component.toast(msg || "裁剪失败");
            }
        });

        InputFile.click();
    };

    /** 
     * 通过微信控件上传图片
     */
    _this.uploaderOnWechat = function (data, callback) {
        let value = _editate_DOM["7"].__data.value;
        let choosed_length = 0;
        if (value != "") {
            choosed_length = Util.type(value) == "string" ? value.split(",").length : value.length;
        }
        let imgsArr = [];

        // 如果达到上限，不再打开上传
        if (data.max_image_length - choosed_length <= 0) {
            return;
        }

        wx.chooseImage({
            count: data.max_image_length - choosed_length, //可上传图片数量
            //sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: data.source_type, // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var localIds = res.localIds;

                var uploadimg = function (imgIndex) {
                    wx.uploadImage({
                        localId: localIds[imgIndex], // 需要上传的图片的本地ID，由chooseImage接口获得
                        isShowProgressTips: 0,// 默认为1，显示进度提示
                        success: function (res) {
                            imgsArr.push(res.serverId);
                            console.log(imgsArr);
                            if (imgsArr.length < localIds.length) {
                                uploadimg(imgIndex + 1);
                            } else {
                                setTimeout(function () {
                                    let _loading = Component.loading("上传中").render();
                                    Api.upload({
                                        mediaIds: JSON.stringify(imgsArr), // 返回图片的服务器端ID
                                    }, function (result) {
                                        _loading.hide(function () {
                                            callback && callback(result.data.map(src => Api.resource(src)));
                                        });
                                    }, function (e) {
                                        _loading.hide(function () {
                                            Component.toast(e.message).render();
                                        });
                                    });
                                }, 100)
                            }
                        },
                        fail: function (error) {
                            Component.toast(error).render();
                            console.log(error);
                        }
                    });
                }
                //开始通过本地获取的localId上传获取对应的serverId最后调用内部服务获取内部服务器上该图片的真实路径
                uploadimg(0);
            },
            fail: function (error) {
                _loading.hide(function () {
                    Component.toast(error).render();
                });
                console.log(error)
            }
        });
    };

    _this.normal = function (template, data = {}) {
        let DOM = Render.create(template);

        DOM.__data = {};
        DOM.__data.value = data.value;
        DOM.__data.value_text = data.value_text;

        let last_value = data.value;
        switch(data.original.type) {
            case "3":
                $(DOM).find(".items-item").on("input", function () {
                    if (this.value != "" && isNaN(this.value)) {
                        this.value = last_value;
                    }
                    last_value = this.value;
                    DOM.__data.value = DOM.__data.value_text = this.value;
                });
                break;
            case "6":
                $(DOM).find(".items-item").on("input", function () {
                    if (this.value != "" && isNaN(this.value)) {
                        this.value = last_value;
                    }
                    last_value = this.value;
                    DOM.__data.value = this.value;
                    DOM.__data.value_text = Util.convertCurrency(DOM.__data.value) || "金额大写";
                    $(DOM).find(".uppercase").html(DOM.__data.value_text);
                });
                break;
            case "51":
            default:
                $(DOM).find(".items-item").on("input", function () {
                    DOM.__data.value = DOM.__data.value_text = this.value;
                });
        }

        return {
            el: DOM
        }
    };

    _this.drawer = function (data) {
        let DOM = Render.create(`<div>
            <div class="items-title">${data.title} ${data.original.limit == 1 ? "" : "（支持多选）"}</div>
            <div class="items-item">${data.placeholder}</div>
        </div>`);

        DOM.__data = {
            value: [],
            value_text: []
        };

        return {
            el: DOM
        };
    };

    _this.drawerTreeDataMap = function (data, options, deep = 1) {
        let trees = [];
        let drawerDOM = Render.create(`<div></div>`);

        data.map(item => {
            let DOM = Render.create(`<div class="member-list">
                <div class="member-list-box">
                    <div class="item-label member-list--label">
                        <div>${item.label}</div>
                        <div class="sub">${item.sub_label || ""}</div>
                    </div>
                    <label class="member-list--checkbox">
                        <input type="checkbox" class="item-checkbox level${deep}-checkbox" data-label="${item.label}" value="${item.id}" ${options.selected.includes(item.id + "") ? "checked" : ""}>
                        <div class="item-checked"></div>
                    </label>
                </div>
                <div class="member-list-children"></div>
            </div>`);

            let $Member_list_box = $(DOM).children(".member-list-box");
            let $Member_list_children = $(DOM).children(".member-list-children");

            $Member_list_box.find(".member-list--checkbox")[0].__data = item;
            $Member_list_box.find(".member-list--checkbox").on("click", function (e) {
                e.stopPropagation();
            });

            // 允许下一级数据时，根据结构渲染下一级内容
            if (deep < options.deep) {
                $Member_list_box.prepend(`<div class="member-list--treei"></div>`);
                let children = _this.drawerTreeDataMap(item.children, options, deep + 1);
                $Member_list_children.append(children);

                $Member_list_box.on("click", function () {
                    if ($(DOM).hasClass("on")) {
                        $(DOM).removeClass("on");
                    } else {
                        if (item.children.length == 0) {
                            Api.getStudent({ id: item.id }, function (result) {
                                let students = [];

                                result.data.map(function (student) {
                                    students.push({
                                        id: student.stud_id,
                                        type: "s",
                                        label: student.stud_name,
                                        children: []
                                    });
                                });

                                item.children = students;

                                children = _this.drawerTreeDataMap(item.children, options, deep + 1);
                                $Member_list_children.append(children);
                                $(DOM).addClass("on");
                            });
                        } else {
                            $(DOM).addClass("on");
                        }
                    }
                });

                $Member_list_box.find(".item-checkbox").on("change", function () {
                    // 选中全部子项
                    $Member_list_children.find(".item-checkbox").prop("checked", this.checked);
                    // 通知上一层
                    $(drawerDOM).trigger("choose", this.checked);
                });

                // 子项选择后，该级是否跟随选中处理
                $(children).on("choose", function (e, checked) {
                    if (!checked) {
                        $Member_list_box.find(".item-checkbox").prop("checked", false);
                    } else {
                        // 如果是子项选中，判断子项是否全部选中，如果全部选中，该级再选中
                        $Member_list_box.find(".item-checkbox").prop("checked", $Member_list_children.find(".item-checkbox:not(:checked)").length == 0);
                    }
                });
            }

            trees.push(DOM);
        });

        $(drawerDOM).append(trees);

        return drawerDOM;
    };

    _this.drawerTree = function (options = {}) {
        options = Object.assign({
            // 最多允许三级
            deep: 3,
            data: [],
            selected: []
        }, options);

        if (options.deep > 3) {
            options.deep = 3;
        }

        return {
            el: _this.drawerTreeDataMap(options.data, options)
        };
    };

    /**
     * 选人抽屉使用这个方法
     */
    _this.editateDrawer = function (data, editate_type, deep = 2) {
        editate_type += "";
        let drawer = _this.drawer(data);
        let DOM = drawer.el;
        let $Items_item = $(DOM).find(".items-item");

        if (data.value != "") {
            DOM.__data.value = data.value.split(",");
        }

        if (data.value_text != "") {
            DOM.__data.value_text = data.value_text.split(",");
            $Items_item.html(DOM.__data.value_text);
        }

        $Items_item.on("click", function () {
            _this.initEditateData(editate_type, data, function (drawer_data) {
                let drawerTree = _this.drawerTree({
                    deep: deep,
                    data: drawer_data,
                    selected: DOM.__data.value
                });
                _editate_DOM[editate_type] = drawerTree.el;

                let body = _editate_DOM[editate_type];
                // let stretch = Render.create(`<div>已选：</div>`);

                Component.drawer({
                    body: body,
                    // stretch: stretch,
                    closeByBlank: false,
                    onComplete: function () {
                        let keyMap = [];

                        $(body).find(`.level${deep}-checkbox:checked`).map(function (index, input) {
                            keyMap.push(input);
                        });

                        // 如果未选择，保留上一次的值
                        // if (keyMap.length == 0) {
                        //     let __deep = deep;
                        //     while(--__deep > 0) {
                        //         if ($(body).find(`.level${__deep}-checkbox:checked`).length > 0) {
                        //             Component.toast(`只能选择一名学生`).render();
                        //             return false;
                        //         }
                        //     }

                        //     return true;
                        // }

                        if (keyMap.length > data.original.limit) {
                            Component.toast(`最多选择${data.original.limit}项`).render();
                            return false;
                        }

                        DOM.__data.value.length = 0;
                        DOM.__data.value_text.length = 0;

                        for (let index in keyMap) {
                            let input = keyMap[index];
                            DOM.__data.value.push(input.value);
                            DOM.__data.value_text.push(input.getAttribute("data-label"));
                        }

                        $Items_item.html(DOM.__data.value_text.join(",") || "请选择");
                    }
                }).render();
            });
        });

        return DOM;
    };

    _this.initEditateData = function (type, data, callback) {
        type += "";

        if (!Util.isEmpty(_editate_data[type])) {
            return callback(_editate_data[type]);
        }

        let options = data.original.options;

        switch(type) {
            case "5":
                callback(Util.likeItemObjectMap(options, (option, index) => {
                    return {
                        id: index,
                        label: option.text,
                        type: ""
                    };
                }));
                break;
            case "90":
            case "91":
                Api.getRange({}, function (result) {
                    var teacher_list = [];
                    if (result.data && result.data.list.length > 0) {
                        teacher_list = result.data.list;
                    }
                    var dep_obj = {};
                    teacher_list.forEach(function (teacher) {
                        if (!dep_obj[teacher.dep_id]) {
                            dep_obj[teacher.dep_id] = {
                                id: teacher.dep_id,
                                label: teacher.dep_name,
                                type: "d",
                                children: []
                            };
                        }
                        if (!dep_obj[teacher.dep_id].children[teacher.tech_id]) {
                            dep_obj[teacher.dep_id].children.push({
                                id: teacher.tech_id,
                                label: teacher.tech_name,
                                type: "t",
                                sub_label: teacher.user_loginname,
                                children: []
                            })
                        }
                    });

                    _editate_data[type] = Object.values(dep_obj);
                    callback(_editate_data[type]);
                });
                break;
            case "92":
            case "93":
                let grades = JSON.parse(sessionStorage.allClass);
                let data = [];

                for (let i in grades) {
                    let grade = grades[i];
                    data.push({
                        id: grade.grade_id,
                        label: grade.grade_name,
                        type: "g",
                        children: grade.classList
                    });
                }

                data.map(item => {
                    let child = [];
                    for(let child_id in item.children) {
                        child.push({
                            id: child_id,
                            label: item.children[child_id].className,
                            type: "c",
                            children: []
                        });
                    }
                    item.children = child;
                });

                _editate_data[type] = data;

                callback(_editate_data[type]);
                break;


        }
    };

    /**
     * 单行输入框
     */
    _this.editate_1 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <input type="text" class="items-item" value="${data.value}" placeholder="${data.placeholder}">
        </div>`, data);
    };

    /**
     * 多行输入框
     */
    _this.editate_2 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <textarea class="items-item" placeholder="${data.placeholder}">${data.value}</textarea>
        </div>`, data);
    };

    /**
     * 数字输入框
     */
    _this.editate_3 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <input type="text" class="items-item" value="${data.value}" placeholder="${data.placeholder}">
        </div>`, data);
    };

    /**
     * 单选下拉框
     */
    _this.editate_4 = function (data = {}) {
        if (Util.isEmpty(data.placeholder)) {
            data.placeholder = "请选择";
        }

        let DOM = Render.create(`<div>
            <div class="items-title">${data.title}</div>
            <select class="form-select items-item"><option value="">${data.placeholder}</option></select>
        </div>`);

        let $Items_item = $(DOM).find(".items-item");
        let keyMap = {"": ""};

        Util.likeItemObjectMap(data.original.options, function (option, index) {
            $Items_item.append(`<option value="${index}" ${data.value == index ? "selected" : ""}>${option.text}</option>`);
            keyMap[index] = option.text;
        });

        DOM.__data = {
            value: "",
            value_text: ""
        };

        $Items_item.on("change", function () {
            // DOM.__data.value = this.value;
            //将单选下拉框的value与value_text保持一致
            DOM.__data.value = keyMap[this.value];
            DOM.__data.value_text = keyMap[this.value];
        });

        return {
            el: DOM
        }
    };

    /**
     * 多选下拉框
     */
    _this.editate_5 = function (data = {}) {
        return {
            el: _this.editateDrawer(data, "5", 1)
        }
    };

    /**
     * 金额输入框
     */
    _this.editate_6 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <input type="text" class="items-item" value="${data.value}" maxlength="15" placeholder="${data.placeholder}">
            <div class="uppercase">${data.original.uppercase ? "金额大写" : ""}</div>
        </div>`, data);
    };

    /**
     * 日期
     */
    _this.editate_61 = function (data = {}) {
        let DOM = Render.create(`<div>
            <div class="items-title">${data.title}</div>
            <input type="text" class="items-item" value="${data.value}" placeholder="${data.placeholder}">
        </div>`);
        DOM.__data = {
            value: data.value || "",
            value_text: data.value_text || ""
        };

        let $Items_item = $(DOM).find(".items-item");

        $Items_item.on("change", function () {
            DOM.__data.value = DOM.__data.value_text = this.value;
        });
        let datetimePickerOptions = {};
        if (data.date_type == '年-月-日 时：分') {
            if (data.value != "") {
                datetimePickerOptions.value = data.value.trim().split(/[-\/: ]/);
            } else {
                let NW = Util.getCalendarDate();
                datetimePickerOptions.value = `${NW.format} ${NW.minuteTimeFormat}`.trim().split(/[-\/: ]/);
            }
            // 绑定日期组件
            $($Items_item).datetimePicker(datetimePickerOptions);
            
        } else if (data.date_type == '年-月-日') {
            // 绑定日期组件
            $($Items_item).calendar({
                value: data.value ? [data.value] : undefined
            })
        }
        return {
            el: DOM
        };
    };

    /**
     * 上传图片
     */
    _this.editate_7 = function (data = {}) {
        let DOM = Render.create(`<div>
            <div class="items-title">${data.title}</div>
            <div class="items-item"></div>
        </div>`);

        DOM.__data = {
            value: data.value,
            value_text: data.value_text
        };

        _editate_DOM["7"] = DOM;

        let PreviewDOM = Render.create(`<div class="img-preview" style="float:left"></div>`);
        let UploadDOM = Render.create(`<div class="img-item img-uploader">
                <i class="img-icon fa fa-camera"></i>
                <span>添加图片</span>
                <div id="clipView"></div>
            </div>`);

        if (DOM.__data.value != "") {
            if (Util.type(DOM.__data.value) == "string") {
                DOM.__data.value = DOM.__data.value.split(",");
            }
            let ImgDOMs = DOM.__data.value.map(src => {
                return _this.editate_7_item(src, data).el;
            });

            _this.editate_7_save(data);
            $(PreviewDOM).append(ImgDOMs);
        }

        $(UploadDOM).on("click", function () {
            data.__pictureSelectMode = "localxcut";
            _this.uploader(data, function (srcs) {
                let ImgDOMs = srcs.map(src => {
                    return _this.editate_7_item(src, data).el;
                });
                $(PreviewDOM).append(ImgDOMs);
                _this.editate_7_save(data);
            });
        });

        $(DOM).children(".items-item").append([PreviewDOM, UploadDOM]);

        return {
            el: DOM
        };
    };

    _this.editate_7_item = function (src, data) {
        let ImgDOM = Render.create(`<div class="img-item">
            <img class="image" src="${src}" alt="">
            <div class="img-item-remove"><i class="remove-img fa fa-trash-o"></i></div>
        </div>`);

        $(ImgDOM).find(".img-item-remove").on("click", function () {
            ImgDOM.parentNode.removeChild(ImgDOM);
            _this.editate_7_save(data);
        });

        return {
            el: ImgDOM
        };
    };

    _this.editate_7_save = function (data) {
        setTimeout(() => {
            let images = [];
            $(_editate_DOM["7"]).find(".img-preview").find(".image").map((index, image) => {
                images.push(image.src);
            });
            _editate_DOM["7"].__data.value = _editate_DOM["7"].__data.value_text = images;
            if (images.length < data.max_image_length) {
                $(_editate_DOM["7"]).find(".img-uploader").show();
            } else {
                $(_editate_DOM["7"]).find(".img-uploader").hide();
            }
        }, 0);
    };

    /**
     * 手写签名
     */
    _this.editate_71 = function (data) {
        let DOM = Render.create(`<div>
            <div class="items-title">${data.title}</div>
            <div class="items-item">${data.placeholder}</div>
        </div>`),
        placeholder = data.placeholder;

        DOM.__data = {
            value: data.value,
            value_text: data.value_text
        };

        _editate_DOM["71"] = DOM;
        if (data.value_text) {
            $(DOM).find('.items-item').html(`<div class="img-item sign">
                <img class="image" src="${data.value_text}" alt="">
                <div class="img-item-remove"><i class="remove-img fa fa-trash-o"></i></div>
            </div>`)
            $(DOM).find('.img-item-remove').on('click', function (e) {
                e.stopPropagation();
                $(this).parents('.items-item').html(placeholder);
                _editate_DOM["71"].__data.value = _editate_DOM["71"].__data.value_text = '';
            })
        }

        let SignDom = Render.create(`<div id="signDialogBox" class="sign-dialog-box">
            <div class="sign-tools-box">
                <div class="sign-tools">
                    <div class="sign-tips">请在下方空白区域签字</div>
                    <div class="sign-tools-items">
                        <span id="signCancelBtn" class="sign-tools-item sign-cancel">取消</span>
                        <span id="signClearBtn" class="sign-tools-item sign-clear">清除</span>
                        <span id="signConfirmBtn" class="sign-tools-item sign-confirm">确定</span>
                    </div>
                </div>
            </div>
            <div id="my_tablet" class="sign-dialog"></div>
        </div>`)

        //记录下当前页面滚动位置
        function pageScrollTop (pointY){
            if (document.scrollingElement) {
                if (!pointY && pointY !== 0) {
                    return document.scrollingElement.scrollTop;
                }
                document.scrollingElement.scrollTop = pointY;
            }
            if (!pointY && pointY !== 0) {
                return Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
            }
            document.documentElement.scrollTop = pointY;
        }
        let htmlScrollTop = pageScrollTop();

        $('body').append(SignDom);
        var tablet = new Tablet("#my_tablet",{
            /* canvas画布是否响应式，默认为true。当设置为响应式后浏览器大小改变后会重新计算canvas画布的宽高，
            并且之前绘制的内容会被清除掉（canvas的一个特性）*/
            // response: true,
            // 签名板的额外class
            extraClass: "",
            //是否在画布上进行涂画
            hasDraw: false,
            // tablet初始化后执行的函数（此时canvas上下文并未初始化
            onInit: function (){
                var that = this,
                    container = this.container;
                that.rotate(90);
                that.setBackgroundColor('#fff');
                $('#signCancelBtn').on('click', function () {
                    that.clear();
                    $(SignDom).removeClass('on');
                    //将页面滚动恢复
                    pageScrollTop(htmlScrollTop);
                })
                $('#signConfirmBtn').on('click', function () {
                    if (!that.hasDraw) {
                        Component.toast("手写签名内容不能为空！").render();
                        $('.toast').css({
                            'z-index': '10010',
                            'transform': 'rotate(90deg)'
                        })
                        setTimeout(() => {
                            $('.toast').css({
                                'z-index': '10',
                                'transform': 'rotate(0deg)'
                            })
                        }, 3000)
                        return false;
                    }
                    var sizeBox = [178, 100];
                    Api.uploadStudImage({
                        base64: that.getBase64(),
                        width: sizeBox[0],
                        height: sizeBox[1],
                    }, function (data) {
                        let changeImgUrl = function (url) {
                            var imgName = url.split(".")[0];
                            imgName = window.location.origin + "/esb/res/pic/" + Math.floor(+imgName / 10000) + "/" + Math.floor(+imgName / 100) + "/" + url;
                            return imgName;
                        }
                        let src = changeImgUrl(data.data);
                        
                        _editate_DOM["71"].__data.value = _editate_DOM["71"].__data.value_text = src;

                        $(SignDom).removeClass('on');
                        //将页面滚动恢复
                        pageScrollTop(htmlScrollTop);
                        that.clear()

                        $(DOM).find('.items-item').html($(`<div class="img-item sign">
                            <img class="image" src="${src}" alt="">
                            <div class="img-item-remove"><i class="remove-img fa fa-trash-o"></i></div>
                        </div>`));
                        $(DOM).find('.img-item-remove').on('click', function (e) {
                            e.stopPropagation();
                            $(this).parents('.items-item').html(placeholder);
                            _editate_DOM["71"].__data.value = _editate_DOM["71"].__data.value_text = '';
                        })
                    });
                })
                $('#signClearBtn').on('click', function () {
                    that.clear();
                })
            },
            //涂画中
            onMoveDraw: function () {
                if (!this.hasDraw) {
                    this.hasDraw = true;
                }
            },
            // 清除画布后执行的函数
            onClear: function() {
                this.setBackgroundColor('#fff');
                this.hasDraw = false;
            }
        })
        $(DOM).find('.items-item').on('click', function () {
            if ($(this).find('img').length > 0) {
                return false;
            }
            //将页面先放置到顶部
            pageScrollTop(0);
            $(SignDom).addClass('on');
        })
        return {
            el: DOM
        };
    },


    /** 
     * 选择附件
     */
    _this.editate_8 = function (data) {
        let DOM = Render.create(`<div>
            <div class="items-title">${data.title}</div>
            <div class="items-item"></div>
        </div>`);

        DOM.__data = {
            value: data.value,
            value_text: data.value_text
        };

        _editate_DOM["8"] = DOM;

        let PreviewDOM = Render.create(`<div class="img-preview" style="float:left"></div>`);
        let SelectDOM = Render.create(`<div class="img-item img-uploader">
                <i class="img-icon fa fa-file"></i>
                <span>添加文件</span>
            </div>`);

        try {
            DOM.__data.value = JSON.parse(DOM.__data.value);
        } catch (error) {
            DOM.__data.value = [];
        }

        let FileDOMs = DOM.__data.value.map(file => {
            return _this.editate_8_item(file, data, DOM).el;
        });

        $(PreviewDOM).append(FileDOMs);
        $(PreviewDOM).append(SelectDOM);

        $(SelectDOM).on("click", function () {
            let netDisk = new oaNetDiskMobile();

            location.hash = "netdisk";

            let windowNetdiskHashChangeEventCallback = function () {
                if (location.hash.slice(1) != "netdisk") {
                    let dom = document.getElementById("oaNetDisk");
                    if (dom) {
                        dom.parentNode.removeChild(dom);
                    }
                    window.removeEventListener("hashchange", windowNetdiskHashChangeEventCallback);
                }
            };

            window.addEventListener("hashchange", windowNetdiskHashChangeEventCallback);

            netDisk.select(function (files, done) {
                let FileDOMs = files.map(file => {
                    // 包含file_id视为重复
                    // 查看id
                    // id相同 -> name相同视为重复
                    // id不同 -> 可以添加

                    if (DOM.__data.value.filter(item => {
                        return item.file_id == file.file_id;
                    }).length > 0) {
                        // file_id 重复
                        return false;
                    };

                    if (DOM.__data.value.filter(item => {
                        return item.id == file.id && item.name== file.name;
                    }).length > 0) {
                        // id重复 name重复
                        return false;
                    }

                    DOM.__data.value.push(file);
                    return _this.editate_8_item(file, data, DOM).el;
                });

                // $(PreviewDOM).append(FileDOMs);
                $(SelectDOM).before(FileDOMs);

                done();
            });
        });

        $(DOM).children(".items-item").append([PreviewDOM, /* SelectDOM */]);

        return {
            el: DOM
        };
    };

    _this.editate_8_item = function (file, data, DOM) {
        let FileDOM = Render.create(`<div class="netdisk-item" style="background-color:transparent">
            <img class="image" src="${file.icon}" alt="">
            <div class="netdisk-item-remove"><i class="remove-img fa fa-trash-o"></i></div>
            <p>${file.name}</p>
        </div>`);

        $(FileDOM).find(".netdisk-item-remove").on("click", function () {
            FileDOM.parentNode.removeChild(FileDOM);
            DOM.__data.value.splice(DOM.__data.value.indexOf(file), 1);
        });

        return {
            el: FileDOM
        };
    };

    /**
     * 选择教师
     */
    _this.editate_90 = function (data = {}) {
        return {
            el: _this.editateDrawer(data, "90")
        };
    };

    /**
     * 选择部门
     */
    _this.editate_91 = function (data = {}) {
        return {
            el: _this.editateDrawer(data, "91", 1)
        };
    };

    _this.editate_92 = function (data = {}) {
        return {
            el: _this.editateDrawer(data, "92", 3)
        };
    };

    _this.editate_93 = function (data = {}) {
        return {
            el: _this.editateDrawer(data, "93")
        };
    };

    /** 
     * 手机号
     */
    _this.editate_31 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <input type="text" class="items-item" value="${data.value}" maxlength="11" placeholder="${data.placeholder}">
        </div>`, data);
    };

    /** 
     * 身份证号
     */
    _this.editate_32 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <input type="text" class="items-item" value="${data.value}" maxlength="18" placeholder="${data.placeholder}">
        </div>`, data);
    };

    /** 
     * 温度输入框
     */
    _this.editate_33 = function (data = {}) {
        return _this.normal(`<div>
            <div class="items-title">${data.title}</div>
            <input type="number" class="items-item" value="${data.value}" maxlength="" placeholder="${data.placeholder}">
        </div>`, data);
    };
    
    /** 
     * 地址
     */
    _this.editate_51 = function (data = {}) {
        if (Util.isEmpty(data.placeholder)) {
            data.placeholder = "请选择";
        }
        console.log(51, data);
        let DOM = Render.create(`<div>
            <div class="items-title">${data.title}</div>
            <div class="items-citychoose"></div>
        </div>`);

        let $citychoose = $(DOM).find(".items-citychoose");

        let createSelect = function (list, values = []) {
            let select = $(`<select class="form-select items-item" style="margin-top:1rem;"><option value="">请选择地区</option></select>`);
            
            let selected = "";
            let cls = list.map(function (city) {
                let $option = $("<option>").val(city.code).text(city.cName);
                if (values[0] == city.code) {
                    selected = city.code;
                    $option.attr("selected", "selected");
                }
                $option[0].preData = city.sList || city.qList || [];
                return $option;
            })
    
            select.find("option").not(":first").empty();
            select.append(cls);

            $citychoose.append(select);

            let showNext = function (value, defaults) {
                select.nextAll().remove();
                let list = select.find("option[value='"+ value +"']")[0].preData;
                if (list.length > 0) {
                    createSelect(list, defaults);
                } else {
                    let $textarea = $(`<textarea style="margin-top:1rem;width:100%;resize:none;height:8rem;padding:1rem;border-color:#ccc;" placeholder="请填写详细地址">${defaults[0] || ""}</textarea>`);
                    $citychoose.append($textarea);
                    setTimeout(function () {
                        $textarea.focus();
                    });
                }
            }

            select.on("change", function () {
                showNext(this.value, []);
            });

            if (selected) {
                showNext(selected, values.slice(1));
            }
        }

        let citys = Object.values(data.preData);
        let v = data.value.split(" ");
        v.push(data.value_text.split(" ").slice(v.length).join(" "));
        createSelect(citys, v);

        DOM.__data = function () {
            let value = [];
            let value_text = [];
            let sels = $citychoose.find("select");
            let text = $citychoose.find("textarea");
            if (sels.length == 1 && sels[0].value == "") {
                value.push("");
                value_text.push("");
            } else {
                for (let i = 0; i < sels.length; i++) {
                    if (sels[i].value == "") {
                        return "详细地区地址填写不完整！";
                    }
                    value.push(sels[i].value);
                    value_text.push($(sels[i]).find("option[value='"+ sels[i].value +"']")[0].innerHTML);
                }
                if (text.length == 0 || text.val() == "") {
                    return "详细地区地址填写不完整！";
                } else {
                    value_text.push(text[0].value);
                }
            }

            return {
                emptyTip: "详细地区地址填写不完整！",
                value: value.join(" "),
                value_text: value_text.join(" ")
            };
        }

        // let $Items_item = $(DOM).find(".items-item");
        // let keyMap = {"": data.placeholder};

        // Util.likeItemObjectMap(data.original.options, function (option, index) {
        //     $Items_item.append(`<option value="${index}" ${data.value == index ? "selected" : ""}>${option.text}</option>`);
        //     keyMap[index] = option.text;
        // });

        // DOM.__data = {
        //     value: "",
        //     value_text: ""
        // };

        // $Items_item.on("change", function () {
        //     DOM.__data.value = this.value;
        //     DOM.__data.value_text = keyMap[this.value];
        // });

        return {
            el: DOM
        }
    };

    return new Editate;
})();
